<?php
namespace Admin\Controller;

class OrderController extends BaseController{
	public $pay = array(1=>'货到付款',2=>'支付宝（未支付）',3=>'支付宝（已支付）',4=>'财付通（未支付）',5=>'财付通（已支付）',6=>'微信支付（未支付）',7=>'微信支付（已支付）',8=>'云支付（未支付）',9=>'云支付（已支付）');
	
	public function index(){
		$Order = D('Order');
		if (IS_POST){
			if (I('post.type') == 0){
				$this->output($Order->all2());
			}else{
				if (I('post.ids')){
					if (I('post.type') == 1){
						$this->output($Order->all3());
					}elseif (I('post.type') == 2){
						//$this->failed('演示站，数据无法批量删除！');
						$this->checkPermit2('Order','recycle2');
						$Order->recycle()  ? $this->success(U(CONTROLLER_NAME.'/index'),'订单已被批量移入回收站！') : $this->failed('订单批量移入回收站失败！');
					}elseif (I('post.type') == 3){
						$this->checkPermit2('Recycle','recover2');
						$Order->recover()  ? $this->success(U(CONTROLLER_NAME.'/index'),'订单批量还原成功！') : $this->failed('订单批量还原失败！');
					}elseif (I('post.type') == 4){
						//$this->failed('演示站，数据无法批量删除！');
						$this->checkPermit2('Recycle','remove2');
						$Order->remove()  ? $this->success(U(CONTROLLER_NAME.'/index'),'订单批量删除成功！') : $this->failed('订单批量删除失败！');
					}elseif (I('post.type') == 5){
						$this->checkPermit2(CONTROLLER_NAME,'state');
						$Order->state()  ? $this->success(U(CONTROLLER_NAME.'/index'),'订单状态修改成功！') : $this->failed('订单状态修改失败！');
					}
				}else{
					$this->failed('您未勾选任何订单！');
				}
			}
		}
		$object = $Order->all($this->page($Order->total()));
		if ($object){
			$Template = D('Template');
			$Manager = D('Manager');
			$Product = D('Product');
			$Logistics = D('Logistics');
			$Ostate = D('Ostate');
			import('Yvjie.QQWry');
			$QQWry = \QQWry::getInstance();
			foreach ($object as $key=>$value){
				if ($value['uid']){
					$object2 = $Manager->one($value['uid']);
					$object[$key]['admin'] = $object2 ? $object2['name'] : '此管理员已被删除';
				}else{
					$object[$key]['admin'] = '前台下单';
				}
				$object3 = $Product->one($value['pid']);
				$object[$key]['pro'] = $object3 ? '<span style="color:'.$object3['color'].';">'.$object3['name'].'（'.$object3['price'].'元）</span>' : '此产品已被删除';
				$object[$key]['total'] = number_format($value['price']*$value['count'],2,'.','');
				$object[$key]['address'] = $value['province'].' '.$value['city'].' '.$value['county'].' '.$value['address'];
				$object4 = $Logistics->one($value['lid']);
				$object[$key]['loginame'] = $object4 ? $object4['name'] : '';
				$object[$key]['logicode'] = $object4 ? $object4['code'] : '';
				$object5 = $Template->one($value['tid']);
				$object[$key]['template'] = $object5 ? $object5['name'] : '此模板已被删除';
				$object6 = $Ostate->one($value['state']);
				$object[$key]['state'] = $object6 ? '<span style="color:'.$object6['color'].';">'.$object6['name'].'</span>' : '此状态已被删除';
				$object[$key]['ip'] = $value['ip'];
				$object[$key]['ipaddr'] = $QQWry->getAddr($value['ip']);
			}
		}
		$this->assign('All',$object);
		$this->field(I('get.field'));
		$this->admin(I('get.uid',-1));
		$this->product(I('get.pid'));
		$this->logistics(I('get.lid'));
		$this->template(I('get.tid'));
		$this->ostate(I('get.state'));
		$this->assign('Pay',$this->pay);
		$this->display('Order/index');
	}
	
	public function add(){
		if (IS_POST){
			$Order = D('Order');
			$object = $Order->insert();
			if (is_numeric($object)){
				$object>0 ? $this->success(U(CONTROLLER_NAME.'/index'),'订单添加成功！') : $this->failed('订单添加失败！');
			}else{
				$this->failed($object);
			}
		}
		$this->product(0,1);
		$this->logistics(0,1);
		$this->template(0,1);
		$this->assign('Pay',$this->pay);
		$this->ostate2();
		$this->display();
	}
	
	public function multi(){
		if (IS_POST){
			$Order = D('Order');
			$object = $Order->multi();
			is_numeric($object) ? $this->success(U(CONTROLLER_NAME.'/index'),'物流单号修改成功！') : $this->failed($object);
		}
		$this->display();
	}
	
	public function update(){
		if (I('get.id')){
			$Order = D('Order');
			if (IS_POST){
				$object = $Order->update();
				if (is_numeric($object)){
					if (I('post.sendmail') == 1){
						$this->sendmail(C('PAY_MAIL_SUBJECT'),C('PAY_MAIL_CONTENT'));
					}elseif (I('post.sendmail') == 2){
						$this->sendmail(C('SEND_MAIL_SUBJECT'),C('SEND_MAIL_CONTENT'));
					}
					$this->success(I('get.from')==1 ? U(CONTROLLER_NAME.'/detail',array('id'=>I('get.id'))) : U(CONTROLLER_NAME.'/index'),'订单修改成功！');
				}else{
					$this->failed($object);
				}
			}
			$object = $Order->one();
			if (!$object) $this->failed('不存在此订单，或没有此订单的管理权限！');
			$this->product($object['pid']);
			$this->logistics($object['lid'],1);
			$this->template($object['tid'],1);
			$this->assign('Pay',$this->pay);
			$this->ostate2($object['state']);
			$object['payUrl'] = $this->payUrl($object['oid']);
			$this->assign('One',$object);
			$this->display('Order/update');
		}else{
			$this->failed('非法操作！');
		}
	}
	
	public function detail(){
		if (I('get.id')){
			$Order = D('Order');
			$object = $Order->one();
			if (!$object) $this->failed('不存在此订单，或没有此订单的管理权限！');
			
			if ($object['uid']){
				$Manager = D('Manager');
				$object2 = $Manager->one($object['uid']);
				$object['manager'] = $object2 ? $object2['name'] : '此管理员已被删除';
			}else{
				$object['manager'] = '前台下单';
			}
			
			$Product = D('Product');
			$object3 = $Product->one($object['pid']);
			$object['product'] = $object3 ? '<span style="color:'.$object3['color'].';">'.$object3['name'].'（'.$object3['price'].'元）</span>' : '此产品已被删除';
			
			$object['total'] = number_format($object['price']*$object['count'],2,'.','');
			
			if ($object['lid']){
				$Logistics = D('Logistics');
				$object4 = $Logistics->one($object['lid']);
				$object['logistics']['name'] = $object4 ? $object4['name'] : '此物流已被删除';
				$object['logistics']['code'] = $object4 ? $object4['code'] : '';
			}else{
				$object['logistics']['name'] = $object['logistics']['code'] = '';
			}
			
			$Template = D('Template');
			$object5 = $Template->one($object['tid']);
			$object['template'] = $object5 ? $object5['name'] : '此模板已被删除';
			
			$Ostate = D('Ostate');
			$object6 = $Ostate->one($object['state']);
			$object['state'] = $object6 ? '<span style="color:'.$object6['color'].';">'.$object6['name'].'</span>' : '此状态已被删除';
			
			import('Yvjie.QQWry');
			$QQWry = \QQWry::getInstance();
			$object['ip'] = $object['ip'].' '.$QQWry->getAddr($object['ip']);
			
			$object['pay'] = $this->pay[$object['pay']];
			$object['payUrl'] = $this->payUrl($object['oid']);
			
			$this->assign('One',$object);
			$this->display('Order/detail');
		}else{
			$this->failed('非法操作！');
		}
	}
	
	public function recycle(){
		if (I('get.id')){
			$Order = D('Order');
			if (IS_POST) $Order->recycle() ? $this->success(I('post.prev'),'订单已被移入回收站！') : $this->failed('订单移入回收站失败！');
			if (!$Order->one()) $this->failed('不存在此订单，或没有此订单的管理权限！');
			$this->confirm('您真的要将这个订单移入回收站么？');
		}else{
			$this->failed('非法操作！');
		}
	}
	
	private function output($object){
		$this->checkPermit2(CONTROLLER_NAME,'output');
		$output = '"订单号","下单管理员","下单模板","姓名","订购产品","成交单价","订购数量","成交总价","联系电话","详细地址","邮政编码","备注","电子邮箱","下单IP","下单来路","下单时间","支付状态","订单状态","物流公司","物流编号",';
		if ($object){
			$Template = D('Template');
			$Manager = D('Manager');
			$Product = D('Product');
			$Logistics = D('Logistics');
			$Ostate = D('Ostate');
			import('Yvjie.QQWry');
			$QQWry = \QQWry::getInstance();
			foreach ($object as $value){
				if ($value['uid']){
					$object2 = $Manager->one($value['uid']);
					$manager = $object2 ? $object2['name'] : '此管理员已被删除';
				}else{
					$manager = '前台下单';
				}
				$object3 = $Product->one($value['pid']);
				if ($value['lid']){
					$object4 = $Logistics->one($value['lid']);
					$loginame = $object4 ? $object4['name'] : '此物流已被删除';
				}else{
					$loginame = '';
				}
				$object5 = $Template->one($value['tid']);
				$object6 = $Ostate->one($value['state']);
				$output .= "\r\n".'"'.$value['oid'].'","'.$manager.'","'.($object5 ? $object5['name'] : '此模板已被删除').'","'.$value['name'].'","'.($object3 ? $object3['name'].'（'.$object3['price'].'元）' : '此产品已被删除').'","'.$value['price'].'元","'.$value['count'].'","'.number_format($value['price']*$value['count'],2,'.','').'元","\''.$value['tel'].'","'.$value['province'].' '.$value['city'].' '.$value['county'].' '.$value['address'].'","\''.$value['post'].'","'.$value['note'].'","'.$value['email'].'","'.($value['ip'] ? $value['ip'].' -- '.$QQWry->getAddr($value['ip']) : '').'","'.htmlspecialchars_decode($value['referrer']).'","'.dateFormat($value['date']).'","'.$this->pay[$value['pay']].'","'.($object6 ? $object6['name'] : '此状态已被删除').'","'.$loginame.'","'.$value['logistics_id'].'",';
			}
		}
		$output = mb_convert_encoding($output,'GBK','UTF-8');
		downFile($output,'order_'.time().'.csv');
		exit;
	}
	
	public function field($n=0){
		$html = '';
		foreach (array('所有字段','订单号','姓名','联系电话','省份','城市','区/县','街道地址','邮政编码','电子邮箱','IP','下单来路','物流编号') as $key=>$value){
			$html .= '<option value="'.$key.'"'.($key==$n ? ' selected' : '').'>'.$value.'</option>';
		}
		$this->assign('Field',$html);
	}
	
	public function admin($n=0){
		$session = session(C('SESSION_KEY'));
		$Manager = D('Manager');
		$object = $Manager->all2();
		$html = '';
		if ($session['level']==1 || ($session['level']==2 && $session['order_permit']!=1)) $html .= '<option value="0"'.($n==0 ? ' selected' : '').'>前台下单</option>';
		if ($object){
			foreach ($object as $value){
				$html .= '<option value="'.$value['id'].'"'.($value['id']==$n ? ' selected' : '').'>'.$value['name'].'</option>';
			}
		}
		$this->assign('Admin2',$html);
	}
	
	public function product($n=0,$flag=0){
		$html = '';
		$Psort = D('Psort');
		$object = $Psort->all2();
		if ($object){
			$Product = D('Product');
			foreach ($object as $value){
				$html .= '<optgroup label="'.$value['name'].'" style="color:'.$value['color'].';">';
				$object2 = $Product->all2($value['id']);
				if ($object2){
					foreach ($object2 as $v){
						if ($n == 0){
							$html .= '<option value="'.$v['id'].'"'.($v['selected']&&$flag ? ' selected' : '').' style="color:'.$v['color'].';" price="'.$v['price'].'">└—'.$v['name'].'（'.$v['price'].'元）</option>';
						}else{
							$html .= '<option value="'.$v['id'].'"'.($v['id']==$n ? ' selected' : '').' style="color:'.$v['color'].';" price="'.$v['price'].'">└—'.$v['name'].'（'.$v['price'].'元）</option>';
						}
					}
				}
				$html .= '</optgroup>';
			}
		}
		$this->assign('Product',$html);
	}
	
	public function logistics($n=0,$flag=0){
		$html = $flag ? '<option value="0">请选择物流公司</option>' : '';
		$Logistics = D('Logistics');
		$object = $Logistics->all2();
		foreach ($object as $value){
			$html .= '<option value="'.$value['id'].'"'.($value['id']==$n ? ' selected' : '').'>'.$value['name'].'</option>';
		}
		$this->assign('Logistics',$html);
	}
	
	public function template($n=0,$flag=0){
		$html = '';
		$Template = D('Template');
		$object = $Template->all2();
		foreach ($object as $value){
			if ($n == 0){
				$html .= '<option value="'.$value['id'].'"'.($value['selected']&&$flag ? ' selected' : '').'>'.$value['name'].'</option>';
			}else{
				$html .= '<option value="'.$value['id'].'"'.($value['id']==$n ? ' selected' : '').'>'.$value['name'].'</option>';
			}
		}
		$this->assign('Template',$html);
	}
	
	public function ostate($n=0){
		$html = '';
		$Ostate = D('Ostate');
		$object = $Ostate->all2();
		foreach ($object as $value){
			$html .= '<option value="'.$value['id'].'"'.($value['id']==$n ? ' selected' : '').' style="color:'.$value['color'].';">'.$value['name'].'</option>';
		}
		$this->assign('Ostate',$html);
	}
	
	private function ostate2($n=0){
		$html = '';
		$Ostate = D('Ostate');
		$object = $Ostate->all2();
		foreach ($object as $value){
			if ($n == 0){
				$html .= '<label style="color:'.$value['color'].';"><input type="radio" name="state" value="'.$value['id'].'"'.($value['selected'] ? ' checked' : '').'>'.$value['name'].'</label>&nbsp;';
			}else{
				$html .= '<label style="color:'.$value['color'].';"><input type="radio" name="state" value="'.$value['id'].'"'.($value['id']==$n ? ' checked' : '').'>'.$value['name'].'</label>&nbsp;';
			}
		}
		$this->assign('Ostate',$html);
	}
	
	private function payUrl($oid){
		return array(
					'alipay'=>C('URL_MODEL') ? C('WEB_URL').'index.php/pay/alipay/oid/'.$oid.'.html' : C('WEB_URL').'index.php?c=pay&a=alipay&oid='.$oid,
					'tenpay'=>C('URL_MODEL') ? C('WEB_URL').'index.php/pay/tenpay/oid/'.$oid.'.html' : C('WEB_URL').'index.php?c=pay&a=tenpay&oid='.$oid,
					'wxpay'=>C('URL_MODEL') ? C('WEB_URL').'index.php/pay/wxpay/oid/'.$oid.'.html' : C('WEB_URL').'index.php?c=pay&a=wxpay&oid='.$oid,
					'yunpay'=>C('URL_MODEL') ? C('WEB_URL').'index.php/pay/yunpay/oid/'.$oid.'.html' : C('WEB_URL').'index.php?c=pay&a=yunpay&oid='.$oid);
	}
	
	private function sendmail($subject,$content){
		$Smtp = D('Smtp');
		if ($Smtp->total() > 0){
			$object = $Smtp->one2();
			if ($object){
				try{
					import('Yvjie.PHPMailer');
					$mail = new \PHPMailer();
					$mail->CharSet = 'UTF-8';
					$mail->IsSMTP();
					$mail->SMTPAuth = true;
					$mail->Port = $object[0]['port'];
					$mail->Host = $object[0]['smtp'];
					$mail->Username = $object[0]['user'];
					$mail->Password = $object[0]['pass'];
					$mail->From = $object[0]['email'];
					$mail->FromName = $object[0]['email'];
					foreach (explode(',',I('post.email')) as $value){
						$mail->AddAddress($value,$mail->FromName);
					}
					$mail->IsHTML(true);
					$mail->Subject = $this->mail($subject);
					$mail->Body = $this->mail($content);
					$mail->Send();
				}catch (phpmailerException $e){
					echo $e->errorMessage();
				}
			}
		}
	}
	
	private function mail($content){
		import('Yvjie.QQWry');
		$QQWry = \QQWry::getInstance();
		
		$Product = D('Product');
		$object = $Product->one(I('post.pid'));
		
		$Logistics = D('Logistics');
		$object2 = $Logistics->one(I('post.lid'));
		
		$Ostate = D('Ostate');
   		$object3 = $Ostate->one(I('post.state'));
		
		return str_replace(array(
			'{oid}',
			'{proname}',
			'{proprice}',
			'{procount}',
			'{prototal}',
			'{name}',
			'{tel}',
			'{province}',
			'{city}',
			'{county}',
			'{address}',
			'{post}',
			'{note}',
			'{email}',
			'{ip}',
			'{referrer}',
			'{alipay}',
			'{tenpay}',
			'{wxpay}',
			'{yunpay}',
			'{pay}',
			'{state}',
			'{loginame}',
			'{logiid}',
			'{logiurl}',
			'{date}'
		),array(
			I('post.oid'),
			$object ? $object['name'] : '',
			$object ? $object['price'] : '',
			I('post.count'),
			$object ? number_format($object['price']*I('post.count'),2,'.','') : '0.00',
			I('post.name'),
			I('post.tel'),
			I('post.province2'),
			I('post.city2'),
			I('post.county2'),
			I('post.address'),
			I('post.post'),
			I('post.note'),
			I('post.email'),
			I('post.ip').' '.$QQWry->getAddr(I('post.ip')),
			I('post.referrer') ? '<a href="'.I('post.referrer').'" target="_blank">'.I('post.referrer').'</a>' : '直接进入',
			C('URL_MODEL') ? C('WEB_URL').'index.php/pay/alipay/oid/'.I('post.oid').'.html' : C('WEB_URL').'index.php?c=pay&a=alipay&oid='.I('post.oid'),
			C('URL_MODEL') ? C('WEB_URL').'index.php/pay/tenpay/oid/'.I('post.oid').'.html' : C('WEB_URL').'index.php?c=pay&a=tenpay&oid='.I('post.oid'),
			C('URL_MODEL') ? C('WEB_URL').'index.php/pay/wxpay/oid/'.I('post.oid').'.html' : C('WEB_URL').'index.php?c=pay&a=wxpay&oid='.I('post.oid'),
			C('URL_MODEL') ? C('WEB_URL').'index.php/pay/yunpay/oid/'.I('post.oid').'.html' : C('WEB_URL').'index.php?c=pay&a=yunpay&oid='.I('post.oid'),
			$this->pay[I('post.pay')],
			$object3 ? '<span style="color:'.$object3['color'].';">'.$object3['name'].'</span>' : '',
			$object2 ? $object2['name'] : '',
			I('post.logistics_id'),
			'http://www.kuaidi100.com/chaxun?com='.($object2 ? $object2['code'] : '').'&nu='.I('post.logistics_id'),
			dateFormat(I('post.date'))
		),$content);
	}
}